import { defineComponent, onActivated, onDeactivated, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useSearchResultStore, useSearchStore } from '@/store/search'
import { useInfinite } from '@/compositions/request/infinite'
import { MEDIA_TYPE } from '@/constant'
import { trackEvent } from '@/gtm'
import API from '@/http'

const Favorite = defineComponent({
  setup() {
    const searchStore = useSearchStore()
    const { toMainViewer, activeRootFetcher, deactiveRootFetcher } = searchStore
    const { searchText, hasSearchText } = storeToRefs(useSearchResultStore())

    const fetcher = ref({
      video: useInfinite({
        request: API.Search.favorite,
        params: { type: MEDIA_TYPE.VIDEO, ...(hasSearchText.value ? { keyword: searchText.value } : {}) },
      }),
      photo: useInfinite({
        request: API.Search.favorite,
        params: { type: MEDIA_TYPE.PHOTO, ...(hasSearchText.value ? { keyword: searchText.value } : {}) },
      }),
    })
    onActivated(() => {
      toMainViewer(fetcher.value)
      activeRootFetcher()
      trackEvent({ key: 37, value: null, meta: { keyword: searchText.value } })
    })
    onDeactivated(() => deactiveRootFetcher())

    watch(searchText, (keyword) => {
      if (!hasSearchText.value) {
        return
      }
      fetcher.value.video.refresh({ newParams: { type: MEDIA_TYPE.VIDEO, keyword } })
      fetcher.value.photo.refresh({ newParams: { type: MEDIA_TYPE.PHOTO, keyword } })
    })
  },
})

export default Favorite
